package com.jhj.provider.bm.controller;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;
import com.jhj.provider.bm.po.b.model.BmOrder;
import com.jhj.provider.bm.service.BmOrderService;
import com.jhj.provider.bm.utils.Constants;
import com.jhj.utils.HttpClientUtil;
import com.jhj.wx.utils.WxUtil;

@RestController
public class OrderQrCodeController {

	@Autowired
	private BmOrderService orderService;

	private Logger logger = LoggerFactory.getLogger(this.getClass());

	/**
	 * @param orderId 订单号
	 * @param resumeFrom 
	 * @param fromId
	 * @param fromMobile 
	 * 
	 * @return string
	 * 
	 */
	@SuppressWarnings("null")
	@RequestMapping(value = "/api/bm/order/gen_resume_qrcode", method = RequestMethod.GET)
	public String getOrderContract(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "orderId") Integer orderId,
			@RequestParam(value = "resumeFrom", required = false, defaultValue = "1") Integer resumeFrom,
			@RequestParam(value = "fromId", required = false, defaultValue = "") Integer fromId,
			@RequestParam(value = "fromMobile", required = false, defaultValue = "") String fromMobile) {

		BmOrder order = orderService.selectByPrimaryKey(orderId);

		if (order == null) {
			return "";
		}
		String qrCode = "";

		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType("image/png");
		
		RestTemplate rest = new RestTemplate();
		String accessToken = WxUtil.getAccessToken(Constants.MP_RESUME_APP_ID, Constants.MP_RESUME_APP_SECERT);
		
		/**
		 * scene格式为
		 * [orderId]-[resumeFrom]-[fromId]-[fromMobile]
		 */
		String scene = orderId + "-" + resumeFrom + "-" + fromId + "-"  + fromMobile;
		
		InputStream inputStream = null;
		OutputStream outputStream = null;
		FileInputStream fis = null;  
		OutputStream os = null;  		
		try {
			String url = "https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken;
			Map<String, Object> param = new HashMap<>();
			param.put("scene", scene);
			param.put("page", "pages/order/detail/detail");
			Map<String,Object> line_color = new HashMap<>();
            line_color.put("r", 0);
            line_color.put("g", 0);
            line_color.put("b", 0);
            param.put("line_color", line_color);
            logger.info("调用生成微信URL接口传参:" + param);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
//            logger.info("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
            byte[] result = entity.getBody();
            logger.info(Base64.encodeBase64String(result));
            inputStream = new ByteArrayInputStream(result);
            String fileName = "/tmp/order-mp-qrcode-"+fromMobile+".png";
            File file = new File(fileName);
            if (!file.exists()){
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
            
            
            fis = new FileInputStream(fileName);  
            os = response.getOutputStream();  
            int count = 0;  
            byte[] buffer = new byte[1024 * 8];  
            while ((count = fis.read(buffer)) != -1) {  
                os.write(buffer, 0, count);  
                os.flush();  
            }  
		} catch (Exception e) {
			logger.error("调用小程序生成微信永久小程序码URL接口异常", e);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}


		return qrCode;
	}
	
	/**
	 * @param orderId
	 * @param resumeFrom
	 * @param fromId
	 * @param fromMobile
	 * @return string
	 * 
	 * */
	@SuppressWarnings("null")
	@RequestMapping(value = "/api/bm/order/gen_resume_qrcode_limit", method = RequestMethod.GET)
	public String genLimit(HttpServletRequest request, HttpServletResponse response,
			@RequestParam(value = "orderId") Integer orderId,
			@RequestParam(value = "resumeFrom", required = false, defaultValue = "1") Integer resumeFrom,
			@RequestParam(value = "fromId", required = false, defaultValue = "") Integer fromId,
			@RequestParam(value = "fromMobile", required = false, defaultValue = "") String fromMobile) {

		BmOrder order = orderService.selectByPrimaryKey(orderId);

		if (order == null) {
			return "";
		}
		String qrCode = "";

		response.setDateHeader("Expires", 0);
		response.setHeader("Cache-Control", "no-store, no-cache, must-revalidate");
		response.addHeader("Cache-Control", "post-check=0, pre-check=0");
		response.setHeader("Pragma", "no-cache");
		response.setContentType("image/png");
		
		RestTemplate rest = new RestTemplate();
		String accessToken = WxUtil.getAccessToken(Constants.MP_RESUME_APP_ID, Constants.MP_RESUME_APP_SECERT);
		
		HashMap<String, Object> params = new HashMap<String, Object>();
		params.put("orderId", orderId);
		params.put("resumeFrom", resumeFrom);
		params.put("fromId", fromId);
		params.put("fromMobile", fromMobile);

		/**
		 * scene格式为
		 * [orderId]-[resumeFrom]-[fromId]-[fromMobile]
		 */
		
		String path = "pages/order/detail/detail?" + HttpClientUtil.getUrlParamsByMap(params);
		InputStream inputStream = null;
		OutputStream outputStream = null;
		FileInputStream fis = null;  
		OutputStream os = null;  
		try {
			String url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=" + accessToken;
			Map<String, Object> param = new HashMap<>();
			param.put("path", path);
			Map<String,Object> line_color = new HashMap<>();
            line_color.put("r", 0);
            line_color.put("g", 0);
            line_color.put("b", 0);
            param.put("line_color", line_color);
            logger.info("调用生成微信URL接口传参:" + param);
            MultiValueMap<String, String> headers = new LinkedMultiValueMap<>();
            HttpEntity requestEntity = new HttpEntity(param, headers);
            ResponseEntity<byte[]> entity = rest.exchange(url, HttpMethod.POST, requestEntity, byte[].class, new Object[0]);
            logger.info("调用小程序生成微信永久小程序码URL接口返回结果:" + entity.getBody());
            byte[] result = entity.getBody();
            logger.info(Base64.encodeBase64String(result));
            inputStream = new ByteArrayInputStream(result);
            String fileName = "/tmp/order-mp-qrcode-limit-"+fromMobile+".png";
            File file = new File(fileName);
            if (!file.exists()){
                file.createNewFile();
            }
            outputStream = new FileOutputStream(file);
            int len = 0;
            byte[] buf = new byte[1024];
            while ((len = inputStream.read(buf, 0, 1024)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.flush();
            
            fis = new FileInputStream(fileName);  
            os = response.getOutputStream();  
            int count = 0;  
            byte[] buffer = new byte[1024 * 8];  
            while ((count = fis.read(buffer)) != -1) {  
                os.write(buffer, 0, count);  
                os.flush();  
            }  
            
            
            
		} catch (Exception e) {
			logger.error("调用小程序生成微信永久小程序码URL接口异常", e);
		} finally {
			if (inputStream != null) {
				try {
					inputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (outputStream != null) {
				try {
					outputStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (os != null) {
				try {
					os.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}


		return qrCode;
	}

}
